let BaaS = window.BaaS

function $isLogin(next) {
    if (!window.$login) {
        BaaS.auth.getCurrentUser().then(() => {
            window.$login = true
            next()
        }).catch(() => {
            next({ name: 'login' })
        })
    } else {
        next()
    }
}

function reset(self, formName) {
    self.$confirm("确认重置？", {
        confirmButtonText: "确定",
        cancelButtonText: "点错了",
        type: "warning",
    }).then(() => {
        self.$refs[formName].resetFields();
    }).catch(err => err)
}

// 查询
function findData(tableName, query, arr, offset) {
    let table = new BaaS.TableObject(tableName)
    if (offset) {
        return table.setQuery(query).select(arr).limit(20).offset(offset).orderBy(['-level', '-created_at']).find()
    } else {
        return table.setQuery(query).select(arr).limit(20).orderBy(['-level', '-created_at']).find()
    }
}

function addData(tableName, data) {
    let table = new BaaS.TableObject(tableName)
    let row = table.create()
    return row.set(data).save()
}

function deleteData(tableName, recordID) {
    let table = new BaaS.TableObject(tableName)
    return table.delete(recordID)
}

function updateData(tableName, recordID, obj, data) {
    let table = new BaaS.TableObject(tableName)
    let row = table.getWithoutData(recordID)
    if (data) {
        row.set(obj, data)
    } else {
        row.set(obj)
    }
    return row.update()
}

export {
    findData,
    addData,
    deleteData,
    updateData,
    $isLogin,
    reset
}